package com.chen.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.entity.ExamHistory;
import com.chen.mapper.ExamChooseMapper;
import com.chen.mapper.ExamHistoryMapper;
import com.chen.service.ExamHistoryService;
import com.chen.vo.ExamChooseVO;
import com.chen.vo.ExamHistoryPaperVO;
import com.chen.vo.ExamHistoryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 考试历史记录
 */
@Service
public class ExamHistoryServiceImpl extends ServiceImpl<ExamHistoryMapper, ExamHistory> implements ExamHistoryService {

    @Autowired
    private ExamChooseMapper examChooseMapper;

    @Override
    public Long getHistoryInfoWithIds(Integer studentId, Integer examPaperId) {
        return baseMapper.findCountByStudentIdAndExamPaperId(studentId, examPaperId);
    }

    @Override
    public void examSubmit(Integer studentId, Integer examPaperId, Integer classId, Integer gradeId) {
        Long historyCount = baseMapper.findCountByStudentIdAndExamPaperId(studentId, examPaperId);
        // 已存在考试记录，不可重复提交
        if (historyCount >0) {
            return;
        }
        //获取当前学生当前试卷所选择的全部答案
        List<ExamChooseVO> chooses = examChooseMapper.findChooseByStudentIdAndExamPaperId(studentId, examPaperId);
        //总分记录
        int sumScore = 0;
        for (ExamChooseVO choose : chooses) {
            // 正确答案
            String rightResult = choose.getRightResult();
            // 所选值
            String result = choose.getResult();
            // 计算分数
            if (result.equals(rightResult)) {
                sumScore += choose.getScore();
            }
        }
        // 本次提交的考试记录信息
        ExamHistory examHistory = ExamHistory.builder().studentId(studentId).examPaperId(examPaperId).score(sumScore).beginTime(new Date()).build();
        // 提交考试记录
        baseMapper.insert(examHistory);
    }

    /**
     * 根据学生id获取学生考试记录
     * @param studentId
     * @return
     */
    @Override
    public List<ExamHistoryPaperVO> findExamHistoryByStudentId(Integer studentId) {
        Assert.isTrue(ObjectUtil.isNotEmpty(studentId), "未获取到学生id");
        return baseMapper.findExamHistoryByStudentId(studentId);
    }

    /**
     * 获取考试记录
     * @return
     */
    @Override
    public List<ExamHistoryVO> findExamHistoryList() {
        return baseMapper.findExamHistoryList();
    }
}
